/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cse.p2p.parser;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class contains all infomation of a peer about a file. This info will be 
 * sent from the a peer to the server when requested and will be manipulated in 
 * the client.
 * 
 * @author TrungHieu
 */
public class PeerInfo {
	private int fileID;
	private int[] pieces;
	private String IP;
	
	private static final String KEY_FILE_ID = "file_id";
	private static final String KEY_PIECES = "pieces";
	private static final String KEY_PEER_IP = "peer_ip";

	public PeerInfo( int fileID, int[] pieces, String IP ) {
		this.fileID = fileID;
		this.pieces = pieces;
		this.IP = IP;
	}

	public String getIP() {
		return IP;
	}

	public int getFileID() {
		return fileID;
	}

	public int[] getPieces() {
		return pieces;
	}
	
	@Override
	public String toString() {
		try {
			JSONObject jsObj = new JSONObject();
			jsObj.put( KEY_FILE_ID, this.fileID );
			jsObj.put( KEY_PIECES, new JSONArray( this.pieces) );
			jsObj.put( KEY_PEER_IP, this.IP );
			return jsObj.toString();
		}
		catch ( JSONException e ) {
			return "";
		}
	}

	public static PeerInfo fromString( String input ) {
		try {
			JSONObject jsObj = new JSONObject( input );
			JSONArray jsArr = jsObj.getJSONArray( KEY_PIECES );
			int[] pieces = new int[jsArr.length()];
			for (int i = 0; i < jsArr.length(); i++ ){
				pieces[i] = jsArr.getInt( i );
			}
			return new PeerInfo( jsObj.getInt( KEY_FILE_ID ),
									 pieces,
									 jsObj.getString( KEY_PEER_IP ) );
		}
		catch ( JSONException e ) {
			return null;
		}
	}
	
	public static List<PeerInfo> listFromString ( String input ){
		try {
			List<PeerInfo> peers = new ArrayList<PeerInfo>();
			JSONArray jsArr = new JSONArray( input );
			for (int i = 0; i < jsArr.length(); i++) {
				peers.add( PeerInfo.fromString( jsArr.getJSONObject( i).toString() ) );
			}
			return peers;
		}
		catch ( JSONException e ){
			return null;
		} 
	}
}
